#include <51func.h>
typedef struct shareRes_s {
    int num;
    pthread_mutex_t mutex;
    pthread_cond_t cond;
} shareRes_t;
void * student(void *arg){
    shareRes_t *pshareRes = (shareRes_t *)arg;
    pthread_mutex_lock(&pshareRes->mutex);
    while(pshareRes->num <= 0){
        // 将if 改成 while 可以避免虚假唤醒
        pthread_cond_wait(&pshareRes->cond,&pshareRes->mutex);
    }
    printf("before, I got a food num = %d\n", pshareRes->num);
    --pshareRes->num;
    printf("after, I got a food num = %d\n", pshareRes->num);
    pthread_mutex_unlock(&pshareRes->mutex);
}
void * cook(void *arg){
    shareRes_t *pshareRes = (shareRes_t *)arg;
    pthread_mutex_lock(&pshareRes->mutex);
    ++pshareRes->num;
    // 通知
    //pthread_cond_signal(&pshareRes->cond);
    pthread_cond_broadcast(&pshareRes->cond);
    pthread_mutex_unlock(&pshareRes->mutex);
}
int main(int argc, char *argv[])
{
    shareRes_t shareRes;
    shareRes.num = 0;
    pthread_mutex_init(&shareRes.mutex,NULL);
    pthread_cond_init(&shareRes.cond,NULL);
    
    pthread_t tid1,tid2,tid3;
    pthread_create(&tid1,NULL,cook,&shareRes);
    pthread_create(&tid2,NULL,student,&shareRes);
    pthread_create(&tid3,NULL,student,&shareRes);
    
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);
    return 0;
}

